package com.lzy.huijinjiazu.mvp.ui.fragment;

import android.os.Bundle;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.LogUtils;
import com.kennyc.view.MultiStateView;
import com.lzy.huijinjiazu.R;
import com.lzy.huijinjiazu.app.EventBusTags;
import com.lzy.huijinjiazu.di.component.DaggerCollectListComponent;
import com.lzy.huijinjiazu.di.module.CollectListModule;
import com.lzy.huijinjiazu.mvp.contract.CollectListContract;
import com.lzy.huijinjiazu.mvp.model.entity.MyCollection;
import com.lzy.huijinjiazu.mvp.presenter.CollectListPresenter;
import com.lzy.huijinjiazu.mvp.ui.adapter.CollectListAdapter;

import org.simple.eventbus.Subscriber;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;


public class CollectListFragment extends BaseFragment<CollectListPresenter> implements CollectListContract.View, CollectListAdapter.OnCheckClickListener {

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_bar)
    TextView mTvBar;
    @BindView(R.id.cb_all)
    CheckBox mCbAll;
    @BindView(R.id.ll_bar)
    LinearLayout mLlBar;
    @BindView(R.id.tv_all_del)
    TextView mTvAllDel;
    @BindView(R.id.tv_del)
    TextView mTvDel;
    @BindView(R.id.ll_del)
    LinearLayout mLlDel;
    @BindView(R.id.multiStateView)
    MultiStateView mMultiStateView;
    private CollectListAdapter mAdapter;
    private int mCurrentPosition = 0;
    private int mSuspensionHeight;
    private Map<Integer, Boolean> map = new HashMap<>();


    public static CollectListFragment newInstance(String type) {
        CollectListFragment fragment = new CollectListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(AppComponent appComponent) {
        DaggerCollectListComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .collectListModule(new CollectListModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_collect_list, container, false);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mTvDel.setBackgroundColor(ContextCompat.getColor(getContext(),R.color.colorAccent));
        mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        initRecyclerView();
        initData();
    }

    private void initData() {
        String json = "[{\n" +
                "\t\t\"goods_id\": \"67\",\n" +
                "\t\t\"goods_name\": \"2017秋装新款连衣裙女韩版修身显瘦包臀背心裙长袖针织两件套装潮\",\n" +
                "\t\t\"goods_price\": \"88.00\",\n" +
                "\t\t\"goods_marketprice\": \"99.00\",\n" +
                "\t\t\"goods_image\": \"1_05592261961000791.png\",\n" +
                "\t\t\"store_id\": \"1\",\n" +
                "\t\t\"points\": \"0\",\n" +
                "\t\t\"cash\": \"0.00\",\n" +
                "\t\t\"fav_id\": \"67\",\n" +
                "\t\t\"fav_time\": \"1515981789\",\n" +
                "\t\t\"in_one_momth\": \"1\",\n" +
                "\t\t\"goods_image_url\": \"http:\\/\\/www.xiaofeizhuanqian.com\\/data\\/upload\\/shop\\/store\\/goods\\/1\\/1_05592261961000791_240.png\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"goods_id\": \"3\",\n" +
                "\t\t\"goods_name\": \"水动力滋养补水精品套（补水五件套）\",\n" +
                "\t\t\"goods_price\": \"3688.00\",\n" +
                "\t\t\"goods_marketprice\": \"3688.00\",\n" +
                "\t\t\"goods_image\": \"27_05584523928228135.jpg\",\n" +
                "\t\t\"store_id\": \"27\",\n" +
                "\t\t\"points\": \"0\",\n" +
                "\t\t\"cash\": \"0.00\",\n" +
                "\t\t\"fav_id\": \"3\",\n" +
                "\t\t\"fav_time\": \"1515981786\",\n" +
                "\t\t\"in_one_momth\": \"1\",\n" +
                "\t\t\"goods_image_url\": \"http:\\/\\/www.xiaofeizhuanqian.com\\/data\\/upload\\/shop\\/store\\/goods\\/27\\/27_05584523928228135_240.jpg\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"goods_id\": \"3\",\n" +
                "\t\t\"goods_name\": \"水动力滋养补水精品套（补水五件套）\",\n" +
                "\t\t\"goods_price\": \"3688.00\",\n" +
                "\t\t\"goods_marketprice\": \"3688.00\",\n" +
                "\t\t\"goods_image\": \"27_05584523928228135.jpg\",\n" +
                "\t\t\"store_id\": \"27\",\n" +
                "\t\t\"points\": \"0\",\n" +
                "\t\t\"cash\": \"0.00\",\n" +
                "\t\t\"fav_id\": \"3\",\n" +
                "\t\t\"fav_time\": \"1515981786\",\n" +
                "\t\t\"in_one_momth\": \"1\",\n" +
                "\t\t\"goods_image_url\": \"http:\\/\\/www.xiaofeizhuanqian.com\\/data\\/upload\\/shop\\/store\\/goods\\/27\\/27_05584523928228135_240.jpg\"\n" +
                "\t}, {\n" +
                "\t\t\"goods_id\": \"3\",\n" +
                "\t\t\"goods_name\": \"水动力滋养补水精品套（补水五件套）\",\n" +
                "\t\t\"goods_price\": \"3688.00\",\n" +
                "\t\t\"goods_marketprice\": \"3688.00\",\n" +
                "\t\t\"goods_image\": \"27_05584523928228135.jpg\",\n" +
                "\t\t\"store_id\": \"27\",\n" +
                "\t\t\"points\": \"0\",\n" +
                "\t\t\"cash\": \"0.00\",\n" +
                "\t\t\"fav_id\": \"3\",\n" +
                "\t\t\"fav_time\": \"1515981786\",\n" +
                "\t\t\"in_one_momth\": \"1\",\n" +
                "\t\t\"goods_image_url\": \"http:\\/\\/www.xiaofeizhuanqian.com\\/data\\/upload\\/shop\\/store\\/goods\\/27\\/27_05584523928228135_240.jpg\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"goods_id\": \"3\",\n" +
                "\t\t\"goods_name\": \"水动力滋养补水精品套（补水五件套）\",\n" +
                "\t\t\"goods_price\": \"3688.00\",\n" +
                "\t\t\"goods_marketprice\": \"3688.00\",\n" +
                "\t\t\"goods_image\": \"27_05584523928228135.jpg\",\n" +
                "\t\t\"store_id\": \"27\",\n" +
                "\t\t\"points\": \"0\",\n" +
                "\t\t\"cash\": \"0.00\",\n" +
                "\t\t\"fav_id\": \"3\",\n" +
                "\t\t\"fav_time\": \"1515981786\",\n" +
                "\t\t\"in_one_momth\": \"0\",\n" +
                "\t\t\"goods_image_url\": \"http:\\/\\/www.xiaofeizhuanqian.com\\/data\\/upload\\/shop\\/store\\/goods\\/27\\/27_05584523928228135_240.jpg\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"goods_id\": \"3\",\n" +
                "\t\t\"goods_name\": \"水动力滋养补水精品套（补水五件套）\",\n" +
                "\t\t\"goods_price\": \"3688.00\",\n" +
                "\t\t\"goods_marketprice\": \"3688.00\",\n" +
                "\t\t\"goods_image\": \"27_05584523928228135.jpg\",\n" +
                "\t\t\"store_id\": \"27\",\n" +
                "\t\t\"points\": \"0\",\n" +
                "\t\t\"cash\": \"0.00\",\n" +
                "\t\t\"fav_id\": \"3\",\n" +
                "\t\t\"fav_time\": \"1515981786\",\n" +
                "\t\t\"in_one_momth\": \"0\",\n" +
                "\t\t\"goods_image_url\": \"http:\\/\\/www.xiaofeizhuanqian.com\\/data\\/upload\\/shop\\/store\\/goods\\/27\\/27_05584523928228135_240.jpg\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"goods_id\": \"3\",\n" +
                "\t\t\"goods_name\": \"水动力滋养补水精品套（补水五件套）\",\n" +
                "\t\t\"goods_price\": \"3688.00\",\n" +
                "\t\t\"goods_marketprice\": \"3688.00\",\n" +
                "\t\t\"goods_image\": \"27_05584523928228135.jpg\",\n" +
                "\t\t\"store_id\": \"27\",\n" +
                "\t\t\"points\": \"0\",\n" +
                "\t\t\"cash\": \"0.00\",\n" +
                "\t\t\"fav_id\": \"3\",\n" +
                "\t\t\"fav_time\": \"1515981786\",\n" +
                "\t\t\"in_one_momth\": \"0\",\n" +
                "\t\t\"goods_image_url\": \"http:\\/\\/www.xiaofeizhuanqian.com\\/data\\/upload\\/shop\\/store\\/goods\\/27\\/27_05584523928228135_240.jpg\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"goods_id\": \"3\",\n" +
                "\t\t\"goods_name\": \"水动力滋养补水精品套（补水五件套）\",\n" +
                "\t\t\"goods_price\": \"3688.00\",\n" +
                "\t\t\"goods_marketprice\": \"3688.00\",\n" +
                "\t\t\"goods_image\": \"27_05584523928228135.jpg\",\n" +
                "\t\t\"store_id\": \"27\",\n" +
                "\t\t\"points\": \"0\",\n" +
                "\t\t\"cash\": \"0.00\",\n" +
                "\t\t\"fav_id\": \"3\",\n" +
                "\t\t\"fav_time\": \"1515981786\",\n" +
                "\t\t\"in_one_momth\": \"0\",\n" +
                "\t\t\"goods_image_url\": \"http:\\/\\/www.xiaofeizhuanqian.com\\/data\\/upload\\/shop\\/store\\/goods\\/27\\/27_05584523928228135_240.jpg\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"goods_id\": \"3\",\n" +
                "\t\t\"goods_name\": \"水动力滋养补水精品套（补水五件套）\",\n" +
                "\t\t\"goods_price\": \"3688.00\",\n" +
                "\t\t\"goods_marketprice\": \"3688.00\",\n" +
                "\t\t\"goods_image\": \"27_05584523928228135.jpg\",\n" +
                "\t\t\"store_id\": \"27\",\n" +
                "\t\t\"points\": \"0\",\n" +
                "\t\t\"cash\": \"0.00\",\n" +
                "\t\t\"fav_id\": \"3\",\n" +
                "\t\t\"fav_time\": \"1515981786\",\n" +
                "\t\t\"in_one_momth\": \"0\",\n" +
                "\t\t\"goods_image_url\": \"http:\\/\\/www.xiaofeizhuanqian.com\\/data\\/upload\\/shop\\/store\\/goods\\/27\\/27_05584523928228135_240.jpg\"\n" +
                "\t},\n" +
                "\t{\n" +
                "\t\t\"goods_id\": \"3\",\n" +
                "\t\t\"goods_name\": \"水动力滋养补水精品套（补水五件套）\",\n" +
                "\t\t\"goods_price\": \"3688.00\",\n" +
                "\t\t\"goods_marketprice\": \"3688.00\",\n" +
                "\t\t\"goods_image\": \"27_05584523928228135.jpg\",\n" +
                "\t\t\"store_id\": \"27\",\n" +
                "\t\t\"points\": \"0\",\n" +
                "\t\t\"cash\": \"0.00\",\n" +
                "\t\t\"fav_id\": \"3\",\n" +
                "\t\t\"fav_time\": \"1515981786\",\n" +
                "\t\t\"in_one_momth\": \"0\",\n" +
                "\t\t\"goods_image_url\": \"http:\\/\\/www.xiaofeizhuanqian.com\\/data\\/upload\\/shop\\/store\\/goods\\/27\\/27_05584523928228135_240.jpg\"\n" +
                "\t}\n" +
                "]";
        Gson gson = new Gson();
        List<MyCollection> data = gson.fromJson(json, new TypeToken<List<MyCollection>>() {
        }.getType());
        mAdapter.addAll(data, true);
        updateSuspensionBar();
        mTvDel.setText(getString(R.string.del, String.valueOf(mAdapter.getSelectCount())));
    }


    private void initRecyclerView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mAdapter = new CollectListAdapter();
        mRecyclerView.setAdapter(mAdapter);


        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                mSuspensionHeight = mLlBar.getHeight();
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                View view = linearLayoutManager.findViewByPosition(mCurrentPosition + 1);
                if (view != null) {
                    if (view.findViewById(R.id.tv_bar).getVisibility() == View.VISIBLE) {
                        if (view.getTop() <= mSuspensionHeight) {
                            mLlBar.setY(-(mSuspensionHeight - view.getTop()));
                        } else {
                            mLlBar.setY(0);
                        }
                    }
                    if (view.getTop() <= 0) {

                    }
                }

                if (mCurrentPosition != linearLayoutManager.findFirstVisibleItemPosition()) {
                    mCurrentPosition = linearLayoutManager.findFirstVisibleItemPosition();
                    mLlBar.setY(0);
                    updateSuspensionBar();

                }
            }
        });
        mAdapter.setOnCheckClickListener(this);
    }


    private void updateSuspensionBar() {
        Log.e("mCurrentPosition", "===============" + mCurrentPosition);
        if (mAdapter.getInfos().size() > 0) {
            mTvBar.setText(mAdapter.getItem(mCurrentPosition).getInOneMomth() == 1 ? "一个月内" : "一个月前");
            mCbAll.setChecked(map.get(mAdapter.getItem(mCurrentPosition).getInOneMomth()) == null ? false : map.get(mAdapter.getItem(mCurrentPosition).getInOneMomth()));
        }
    }

    @OnClick({R.id.cb_all, R.id.tv_all_del, R.id.tv_del})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cb_all:
                checkAll();
                break;
            case R.id.tv_all_del:
                break;
            case R.id.tv_del:
                String ids = mAdapter.getIds();

                break;
        }

    }


    //全选组1或0
    private void checkAll() {
        map.put(mAdapter.getItem(mCurrentPosition).getInOneMomth(), mCbAll.isChecked());
        if (mAdapter.getInfos().size() > 0) {
            List<MyCollection> data = mAdapter.getInfos();
            for (MyCollection myCollection : data) {
                if (myCollection.getInOneMomth() == mAdapter.getItem(mCurrentPosition).getInOneMomth()) {
                    myCollection.setCheck(mCbAll.isChecked());
                }
            }
            mTvDel.setText(getString(R.string.del, String.valueOf(mAdapter.getSelectCount())));
            mAdapter.notifyDataSetChanged();
        }
    }


    //父activity通知子fragment显示或隐藏组checkbox
    public void checkEdit(boolean isEdit) {
        mLlDel.setVisibility(isEdit ? View.VISIBLE : View.GONE);
        mCbAll.setVisibility(isEdit ? View.VISIBLE : View.GONE);
        List<MyCollection> data = mAdapter.getInfos();
        for (MyCollection myCollection : data) {
            myCollection.setEdit(isEdit);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Subscriber(tag = EventBusTags.COLLECT_STATE)
    public void collectState(Message message) {
        if (message.what == 0) {
            checkEdit((Boolean) message.obj);
        }
    }

    @Override
    public boolean useEventBus() {
        return true;
    }


    @Override
    public void setOnItemClick(int inOneMomth, String id, boolean isCheck, CheckBox checkBox) {
        boolean headCheck = true;
        for (int i = 0; i < mAdapter.getInfos().size(); i++) {
            if (inOneMomth == 0) {
                if (mAdapter.getInfos().get(i).getInOneMomth() == 0) {
                    if (!mAdapter.getInfos().get(i).isCheck()) {
                        headCheck = false;
                        break;
                    }
                }
            } else {
                if (mAdapter.getInfos().get(i).getInOneMomth() == 1) {
                    if (!mAdapter.getInfos().get(i).isCheck()) {
                        headCheck = false;
                        break;
                    }

                }
            }
        }
        mCbAll.setChecked(headCheck);
        map.put(inOneMomth, headCheck);
        mosaicIds(isCheck, id);
        mTvDel.setText(getString(R.string.del, String.valueOf(mAdapter.getSelectCount())));
        mAdapter.notifyDataSetChanged();
    }

    private int totalDelNum;
    private String ids = "";
    private String totalIds = "";

    @Override
    public void setOnGroupClick(int position, int inOneMomth, boolean isCheck) {
        setMap(position, isCheck);
        List<MyCollection> data = mAdapter.getInfos();
        for (int i = 0; i < data.size(); i++) {
            if (inOneMomth == data.get(i).getInOneMomth()) {
            }
        }
        mTvDel.setText(getString(R.string.del, String.valueOf(mAdapter.getSelectCount())));
    }

    @Override
    public void setOnCheckChange(int position, boolean b) {
    }

    public void setMap(int position, boolean isCheck) {
        map.put(mAdapter.getItem(position).getInOneMomth(), isCheck);
    }

    private void mosaicIds(boolean isCheck, String id) {
        if (isCheck) {
            if (!ids.contains(id + ","))
                ids += id + ",";
        } else {
            ids = ids.replace(id + ",", "");
        }
    }

}
